{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Want to guess what the most popular pandas-related question on StackOverflow is about? http://stackoverflow.com/questions/14262433/large-data-work-flows-using-pandas\n",
    "\n",
    "The strength of pandas really is in medium-data analytics, which can roughly be described as \"datasets that fit in memory, comfortable\".\n",
    "Depending on your data needs (and ability to buy time on a big [EC2 instance](https://aws.amazon.com/ec2/instance-types/) with, say, 244 GiB of RAM), this section may not apply to you.\n",
    "\n",
    "Pandas is not meant for \"Big Data\", but then again you probably don't have big data."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Chunking and Iteration\n",
    "\n",
    "The first potential operation for handling larger-than-memory data is chunking or batching your data, and iterating over each batch.\n",
    "This immediately rules out algorithms that require the full dataset to be in memory at once, but with a bit of cleverness you can work around that limitation for many problems."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'201401'"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.Timestamp('2014-01-01').strftime(\"%Y%m\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from distributed import Executor\n",
    "\n",
    "executor = Executor('127.0.0.1:8786')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from distributed.diagnostics import progress"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "progress?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import requests"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def download_month(month):\n",
    "    os.makedirs('comext', exist_ok=True)\n",
    "    base = (\"http://ec.europa.eu/eurostat/estat-navtree-portlet-prod/\"\n",
    "            \"BulkDownloadListing?sort=1&\"\n",
    "            \"downfile=comext%2F2015S1%2Fdata%2Fnc{:%Y%m}.7z\")\n",
    "    r = requests.get(base.format(month), stream=True)\n",
    "    filename = 'comext/{:%Y-%m}.tsv.7z'.format(month)\n",
    "    with open(filename, 'wb') as f:\n",
    "        for chunk in r.iter_content(chunk_size=1024):\n",
    "            if chunk:\n",
    "                f.write(chunk)\n",
    "    return filename\n",
    "\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "dates = pd.date_range(start='2012-01-01', end='2014-12-01', freq='m')\n",
    "futures = executor.map(download_month, dates)\n",
    "progress(*futures)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "!rename -S .gz .7z comext/*.gz"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "rm nc201401.dat"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "7-Zip [64] 15.09 beta : Copyright (c) 1999-2015 Igor Pavlov : 2015-10-16\n",
      "p7zip Version 15.09 beta (locale=utf8,Utf16=on,HugeFiles=on,64 bits,4 CPUs x64)\n",
      "\n",
      "Scanning the drive for archives:\n",
      "  0M Scan\b\b\b\b\b\b\b\b\b         \b\b\b\b\b\b\b\b\b1 file, 38021410 bytes (37 MiB)\n",
      "\n",
      "Extracting archive: comext/2014-01.tsv.7z\n",
      "--\n",
      "Path = comext/2014-01.tsv.7z\n",
      "Type = 7z\n",
      "Physical Size = 38021410\n",
      "Headers Size = 126\n",
      "Method = LZMA:26\n",
      "Solid = -\n",
      "Blocks = 1\n",
      "\n",
      "  0%\b\b\b\b    \b\b\b\b  5% - nc201401.dat\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b                   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 10% - nc201401.dat\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b                   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 16% - nc201401.dat\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b                   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 22% - nc201401.dat\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b                   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 27% - nc201401.dat\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b                   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 34% - nc201401.dat\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b                   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 39% - nc201401.dat\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b                   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 42% - nc201401.dat\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b                   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 48% - nc201401.dat\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b                   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 53% - nc201401.dat\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b                   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 56% - nc201401.dat\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b                   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 60% - nc201401.dat\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b                   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 65% - nc201401.dat\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b                   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 68% - nc201401.dat\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b                   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 73% - nc201401.dat\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b                   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 79% - nc201401.dat\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b                   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 83% - nc201401.dat\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b                   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 87% - nc201401.dat\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b                   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 92% - nc201401.dat\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b                   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b 96% - nc201401.dat\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b                   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b100% 1\b\b\b\b\b\b      \b\b\b\b\b\bEverything is Ok\n",
      "\n",
      "Size:       244210771\n",
      "Compressed: 38021410\n"
     ]
    }
   ],
   "source": [
    "!7z x -ocomext comext/*.7z"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "df = pd.read_csv('comext/nc201401.dat', dtype={'DECLARANT': 'object'})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 90,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<table border=\"0\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>DECLARANT</th>\n",
       "      <th>PARTNER</th>\n",
       "      <th>PRODUCT_NC</th>\n",
       "      <th>FLOW</th>\n",
       "      <th>STAT_REGIME</th>\n",
       "      <th>PERIOD</th>\n",
       "      <th>VALUE_1000ECU</th>\n",
       "      <th>QUANTITY_TON</th>\n",
       "      <th>SUP_QUANTITY</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>001</td>\n",
       "      <td>3</td>\n",
       "      <td>01</td>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "      <td>201401</td>\n",
       "      <td>2910.83</td>\n",
       "      <td>521.5</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>001</td>\n",
       "      <td>3</td>\n",
       "      <td>01</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>201401</td>\n",
       "      <td>1234.51</td>\n",
       "      <td>250.7</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>001</td>\n",
       "      <td>3</td>\n",
       "      <td>01012100</td>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "      <td>201401</td>\n",
       "      <td>92.11</td>\n",
       "      <td>2.0</td>\n",
       "      <td>4.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>001</td>\n",
       "      <td>3</td>\n",
       "      <td>01012100</td>\n",
       "      <td>2</td>\n",
       "      <td>4</td>\n",
       "      <td>201401</td>\n",
       "      <td>10.55</td>\n",
       "      <td>0.5</td>\n",
       "      <td>1.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>001</td>\n",
       "      <td>3</td>\n",
       "      <td>01012990</td>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "      <td>201401</td>\n",
       "      <td>32.97</td>\n",
       "      <td>1.1</td>\n",
       "      <td>2.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  DECLARANT  PARTNER PRODUCT_NC  FLOW  STAT_REGIME  PERIOD  VALUE_1000ECU  \\\n",
       "0       001        3         01     1            4  201401        2910.83   \n",
       "1       001        3         01     2            4  201401        1234.51   \n",
       "2       001        3   01012100     1            4  201401          92.11   \n",
       "3       001        3   01012100     2            4  201401          10.55   \n",
       "4       001        3   01012990     1            4  201401          32.97   \n",
       "\n",
       "   QUANTITY_TON  SUP_QUANTITY  \n",
       "0         521.5           NaN  \n",
       "1         250.7           NaN  \n",
       "2           2.0           4.0  \n",
       "3           0.5           1.0  \n",
       "4           1.1           2.0  "
      ]
     },
     "execution_count": 90,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import dask.dataframe as dd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import zipfile"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "zf = zipfile.ZipFile('ml-latest.zip')\n",
    "\n",
    "zf.extractall()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "README.txt   links.csv    movies.csv   ratings.csv  tags.csv\r\n"
     ]
    }
   ],
   "source": [
    "ls ml-latest/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "df = pd.read_csv('ml-latest/ratings.csv')\n",
    "df['timestamp'] = pd.to_datetime(df.timestamp, unit='s')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "ratings = dd.from_pandas(df, npartitions=100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<table border=\"0\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>userId</th>\n",
       "      <th>movieId</th>\n",
       "      <th>rating</th>\n",
       "      <th>timestamp</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>169</td>\n",
       "      <td>2.5</td>\n",
       "      <td>2008-03-07 22:08:14</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1</td>\n",
       "      <td>2471</td>\n",
       "      <td>3.0</td>\n",
       "      <td>2008-03-07 22:03:58</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>1</td>\n",
       "      <td>48516</td>\n",
       "      <td>5.0</td>\n",
       "      <td>2008-03-07 22:03:55</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2</td>\n",
       "      <td>2571</td>\n",
       "      <td>3.5</td>\n",
       "      <td>2015-07-06 06:50:33</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2</td>\n",
       "      <td>109487</td>\n",
       "      <td>4.0</td>\n",
       "      <td>2015-07-06 06:51:36</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   userId  movieId  rating           timestamp\n",
       "0       1      169     2.5 2008-03-07 22:08:14\n",
       "1       1     2471     3.0 2008-03-07 22:03:58\n",
       "2       1    48516     5.0 2008-03-07 22:03:55\n",
       "3       2     2571     3.5 2015-07-06 06:50:33\n",
       "4       2   109487     4.0 2015-07-06 06:51:36"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ratings.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "s = df.head(1000000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "s2 = dd.from_pandas(s, npartitions=20)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def sessionize(ts):\n",
    "    return (ts.sort_values().diff() >= pd.Timedelta(1, unit='h')).fillna(True).cumsum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from dask.diagnostics import Profiler, ResourceProfiler, CacheProfiler"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "with Profiler() as prof, ResourceProfiler() as rprof:\n",
    "    out = ratings.groupby('userId').timestamp.apply(sessionize, columns='timstamp').compute()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<bokeh.plotting.figure.Figure at 0x139a92ba8>"
      ]
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "prof.visualize()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<bokeh.plotting.figure.Figure at 0x113cb8860>"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rprof.visualize()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 7.8 s, sys: 143 ms, total: 7.94 s\n",
      "Wall time: 7.93 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "userId        \n",
       "1       2           0\n",
       "        1           0\n",
       "        0           0\n",
       "2       3           0\n",
       "        4           0\n",
       "                 ... \n",
       "10790   999616    111\n",
       "        999595    111\n",
       "        999596    111\n",
       "        999758    112\n",
       "        999475    113\n",
       "dtype: int64"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "s.groupby('userId').timestamp.apply(sessionize)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 1.35 s, sys: 24 ms, total: 1.37 s\n",
      "Wall time: 1.38 s\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "userId  userId  movieId\n",
       "1       1       48516      0\n",
       "                2471       0\n",
       "                169        0\n",
       "2       2       2571       0\n",
       "                109487     0\n",
       "                          ..\n",
       "1052    1052    50872      1\n",
       "                59315      1\n",
       "                47099      2\n",
       "                1246       2\n",
       "                356        2\n",
       "dtype: int64"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%%time\n",
    "s2.groupby(level=0).timestamp.apply(sessionize)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "userId          \n",
       "1       2           0\n",
       "        1           0\n",
       "        0           0\n",
       "2       3           0\n",
       "        4           0\n",
       "                   ..\n",
       "247753  22884374    0\n",
       "        22884369    0\n",
       "        22884373    0\n",
       "        22884368    1\n",
       "        22884365    1\n",
       "dtype: int64"
      ]
     },
     "execution_count": 67,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.groupby(['userId']).timestamp.apply(sessionize)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'str' object has no attribute '_name'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-43-4bc4de3fdded>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mratings\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgroupby\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'userId'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrating\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mapply\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmean\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;32m/Users/tom.augspurger/Envs/blog/lib/python3.5/site-packages/dask/dataframe/groupby.py\u001b[0m in \u001b[0;36mapply\u001b[0;34m(self, func, columns)\u001b[0m\n\u001b[1;32m    205\u001b[0m         \"\"\"\n\u001b[1;32m    206\u001b[0m         \u001b[0;31m# df = set_index(self.df, self.index, **self.kwargs)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 207\u001b[0;31m         \u001b[0;32mif\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_name\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdf\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_name\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    208\u001b[0m             return map_partitions(_groupby_level0_getitem_apply,\n\u001b[1;32m    209\u001b[0m                                   \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mdf\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mkey\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfunc\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mAttributeError\u001b[0m: 'str' object has no attribute '_name'"
     ]
    }
   ],
   "source": [
    "ratings.groupby('userId').rating.apply(np.mean)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<table border=\"0\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>userId</th>\n",
       "      <th>movieId</th>\n",
       "      <th>rating</th>\n",
       "      <th>timestamp</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>169</td>\n",
       "      <td>2.5</td>\n",
       "      <td>2008-03-07 22:08:14</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1</td>\n",
       "      <td>2471</td>\n",
       "      <td>3.0</td>\n",
       "      <td>2008-03-07 22:03:58</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>1</td>\n",
       "      <td>48516</td>\n",
       "      <td>5.0</td>\n",
       "      <td>2008-03-07 22:03:55</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2</td>\n",
       "      <td>2571</td>\n",
       "      <td>3.5</td>\n",
       "      <td>2015-07-06 06:50:33</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2</td>\n",
       "      <td>109487</td>\n",
       "      <td>4.0</td>\n",
       "      <td>2015-07-06 06:51:36</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>95</th>\n",
       "      <td>4</td>\n",
       "      <td>1966</td>\n",
       "      <td>3.0</td>\n",
       "      <td>2002-11-19 21:02:20</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>96</th>\n",
       "      <td>4</td>\n",
       "      <td>2132</td>\n",
       "      <td>5.0</td>\n",
       "      <td>2002-11-19 20:26:41</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>97</th>\n",
       "      <td>4</td>\n",
       "      <td>2174</td>\n",
       "      <td>4.0</td>\n",
       "      <td>2004-06-29 21:35:21</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>98</th>\n",
       "      <td>4</td>\n",
       "      <td>2248</td>\n",
       "      <td>4.0</td>\n",
       "      <td>2002-11-19 20:45:14</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>99</th>\n",
       "      <td>4</td>\n",
       "      <td>2289</td>\n",
       "      <td>4.0</td>\n",
       "      <td>2002-11-19 20:38:55</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>100 rows × 4 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "    userId  movieId  rating           timestamp\n",
       "0        1      169     2.5 2008-03-07 22:08:14\n",
       "1        1     2471     3.0 2008-03-07 22:03:58\n",
       "2        1    48516     5.0 2008-03-07 22:03:55\n",
       "3        2     2571     3.5 2015-07-06 06:50:33\n",
       "4        2   109487     4.0 2015-07-06 06:51:36\n",
       "..     ...      ...     ...                 ...\n",
       "95       4     1966     3.0 2002-11-19 21:02:20\n",
       "96       4     2132     5.0 2002-11-19 20:26:41\n",
       "97       4     2174     4.0 2004-06-29 21:35:21\n",
       "98       4     2248     4.0 2002-11-19 20:45:14\n",
       "99       4     2289     4.0 2002-11-19 20:38:55\n",
       "\n",
       "[100 rows x 4 columns]"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (<ipython-input-32-b6172370324e>, line 3)",
     "output_type": "error",
     "traceback": [
      "\u001b[0;36m  File \u001b[0;32m\"<ipython-input-32-b6172370324e>\"\u001b[0;36m, line \u001b[0;32m3\u001b[0m\n\u001b[0;31m    =======\u001b[0m\n\u001b[0m     ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "# %load ml-latest/README.txt\n",
    "Summary\n",
    "=======\n",
    "\n",
    "This dataset (ml-latest) describes 5-star rating and free-text tagging activity from [MovieLens](http://movielens.org), a movie recommendation service. It contains 22884377 ratings and 586994 tag applications across 34208 movies. These data were created by 247753 users between January 09, 1995 and January 29, 2016. This dataset was generated on January 29, 2016.\n",
    "\n",
    "Users were selected at random for inclusion. All selected users had rated at least 1 movies. No demographic information is included. Each user is represented by an id, and no other information is provided.\n",
    "\n",
    "The data are contained in four files, `links.csv`, `movies.csv`, `ratings.csv` and `tags.csv`. More details about the contents and use of all these files follows.\n",
    "\n",
    "This is a *development* dataset. As such, it may change over time and is not an appropriate dataset for shared research results. See available *benchmark* datasets if that is your intent.\n",
    "\n",
    "This and other GroupLens data sets are publicly available for download at <http://grouplens.org/datasets/>.\n",
    "\n",
    "\n",
    "Usage License\n",
    "=============\n",
    "\n",
    "Neither the University of Minnesota nor any of the researchers involved can guarantee the correctness of the data, its suitability for any particular purpose, or the validity of results based on the use of the data set. The data set may be used for any research purposes under the following conditions:\n",
    "\n",
    "* The user may not state or imply any endorsement from the University of Minnesota or the GroupLens Research Group.\n",
    "* The user must acknowledge the use of the data set in publications resulting from the use of the data set (see below for citation information).\n",
    "* The user may not redistribute the data without separate permission.\n",
    "* The user may not use this information for any commercial or revenue-bearing purposes without first obtaining permission from a faculty member of the GroupLens Research Project at the University of Minnesota.\n",
    "* The executable software scripts are provided \"as is\" without warranty of any kind, either expressed or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. The entire risk as to the quality and performance of them is with you. Should the program prove defective, you assume the cost of all necessary servicing, repair or correction.\n",
    "\n",
    "In no event shall the University of Minnesota, its affiliates or employees be liable to you for any damages arising out of the use or inability to use these programs (including but not limited to loss of data or data being rendered inaccurate).\n",
    "\n",
    "If you have any further questions or comments, please email <grouplens-info@cs.umn.edu>\n",
    "\n",
    "\n",
    "Citation\n",
    "========\n",
    "\n",
    "To acknowledge use of the dataset in publications, please cite the following paper:\n",
    "\n",
    "> F. Maxwell Harper and Joseph A. Konstan. 2015. The MovieLens Datasets: History and Context. ACM Transactions on Interactive Intelligent Systems (TiiS) 5, 4, Article 19 (December 2015), 19 pages. DOI=<http://dx.doi.org/10.1145/2827872>\n",
    "\n",
    "\n",
    "Further Information About GroupLens\n",
    "===================================\n",
    "\n",
    "GroupLens is a research group in the Department of Computer Science and Engineering at the University of Minnesota. Since its inception in 1992, GroupLens's research projects have explored a variety of fields including:\n",
    "\n",
    "* recommender systems\n",
    "* online communities\n",
    "* mobile and ubiquitious technologies\n",
    "* digital libraries\n",
    "* local geographic information systems\n",
    "\n",
    "GroupLens Research operates a movie recommender based on collaborative filtering, MovieLens, which is the source of these data. We encourage you to visit <http://movielens.org> to try it out! If you have exciting ideas for experimental work to conduct on MovieLens, send us an email at <grouplens-info@cs.umn.edu> - we are always interested in working with external collaborators.\n",
    "\n",
    "\n",
    "Content and Use of Files\n",
    "========================\n",
    "\n",
    "Formatting and Encoding\n",
    "-----------------------\n",
    "\n",
    "The dataset files are written as [comma-separated values](http://en.wikipedia.org/wiki/Comma-separated_values) files with a single header row. Columns that contain commas (`,`) are escaped using double-quotes (`\"`). These files are encoded as UTF-8. If accented characters in movie titles or tag values (e.g. Misérables, Les (1995)) display incorrectly, make sure that any program reading the data, such as a text editor, terminal, or script, is configured for UTF-8.\n",
    "\n",
    "User Ids\n",
    "--------\n",
    "\n",
    "MovieLens users were selected at random for inclusion. Their ids have been anonymized. User ids are consistent between `ratings.csv` and `tags.csv` (i.e., the same id refers to the same user across the two files).\n",
    "\n",
    "Movie Ids\n",
    "---------\n",
    "\n",
    "Only movies with at least one rating or tag are included in the dataset. These movie ids are consistent with those used on the MovieLens web site (e.g., id `1` corresponds to the URL <https://movielens.org/movies/1>). Movie ids are consistent between `ratings.csv`, `tags.csv`, `movies.csv`, and `links.csv` (i.e., the same id refers to the same movie across these four data files).\n",
    "\n",
    "\n",
    "Ratings Data File Structure (ratings.csv)\n",
    "-----------------------------------------\n",
    "\n",
    "All ratings are contained in the file `ratings.csv`. Each line of this file after the header row represents one rating of one movie by one user, and has the following format:\n",
    "\n",
    "    userId,movieId,rating,timestamp\n",
    "\n",
    "The lines within this file are ordered first by userId, then, within user, by movieId.\n",
    "\n",
    "Ratings are made on a 5-star scale, with half-star increments (0.5 stars - 5.0 stars).\n",
    "\n",
    "Timestamps represent seconds since midnight Coordinated Universal Time (UTC) of January 1, 1970.\n",
    "\n",
    "Tags Data File Structure (tags.csv)\n",
    "-----------------------------------\n",
    "\n",
    "All tags are contained in the file `tags.csv`. Each line of this file after the header row represents one tag applied to one movie by one user, and has the following format:\n",
    "\n",
    "    userId,movieId,tag,timestamp\n",
    "\n",
    "The lines within this file are ordered first by userId, then, within user, by movieId.\n",
    "\n",
    "Tags are user-generated metadata about movies. Each tag is typically a single word or short phrase. The meaning, value, and purpose of a particular tag is determined by each user.\n",
    "\n",
    "Timestamps represent seconds since midnight Coordinated Universal Time (UTC) of January 1, 1970.\n",
    "\n",
    "Movies Data File Structure (movies.csv)\n",
    "---------------------------------------\n",
    "\n",
    "Movie information is contained in the file `movies.csv`. Each line of this file after the header row represents one movie, and has the following format:\n",
    "\n",
    "    movieId,title,genres\n",
    "\n",
    "Movie titles are entered manually or imported from <https://www.themoviedb.org/>, and include the year of release in parentheses. Errors and inconsistencies may exist in these titles.\n",
    "\n",
    "Genres are a pipe-separated list, and are selected from the following:\n",
    "\n",
    "* Action\n",
    "* Adventure\n",
    "* Animation\n",
    "* Children's\n",
    "* Comedy\n",
    "* Crime\n",
    "* Documentary\n",
    "* Drama\n",
    "* Fantasy\n",
    "* Film-Noir\n",
    "* Horror\n",
    "* Musical\n",
    "* Mystery\n",
    "* Romance\n",
    "* Sci-Fi\n",
    "* Thriller\n",
    "* War\n",
    "* Western\n",
    "* (no genres listed)\n",
    "\n",
    "Links Data File Structure (links.csv)\n",
    "---------------------------------------\n",
    "\n",
    "Identifiers that can be used to link to other sources of movie data are contained in the file `links.csv`. Each line of this file after the header row represents one movie, and has the following format:\n",
    "\n",
    "    movieId,imdbId,tmdbId\n",
    "\n",
    "movieId is an identifier for movies used by <https://movielens.org>. E.g., the movie Toy Story has the link <https://movielens.org/movies/1>.\n",
    "\n",
    "imdbId is an identifier for movies used by <http://www.imdb.com>. E.g., the movie Toy Story has the link <http://www.imdb.com/title/tt0114709/>.\n",
    "\n",
    "tmdbId is an identifier for movies used by <https://www.themoviedb.org>. E.g., the movie Toy Story has the link <https://www.themoviedb.org/movie/862>.\n",
    "\n",
    "Use of the resources listed above is subject to the terms of each provider.\n",
    "\n",
    "Cross-Validation\n",
    "----------------\n",
    "\n",
    "Prior versions of the MovieLens dataset included either pre-computed cross-folds or scripts to perform this computation. We no longer bundle either of these features with the dataset, since most modern toolkits provide this as a built-in feature. If you wish to learn about standard approaches to cross-fold computation in the context of recommender systems evaluation, see [LensKit](http://lenskit.org) for tools, documentation, and open-source code examples.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
